<template>
  <el-row :gutter="20">
    <el-dialog title="手机号码验证" :visible.sync="validPhoneDialog" width="30%" :wrapper-closable="false" :before-close="closeValidPhone">
      <el-form :model="validPhoneForm">
        <el-form-item label="手机号码" label-width="100px">
          <el-input v-model="validPhoneForm.phone" auhonetocomplete="off" disabled></el-input>
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="验证码" label-width="100px" style="flex:1;">
            <el-input v-model="validPhoneForm.code" autocomplete="off" style="width:300px"></el-input>
          </el-form-item>
          <el-button @click="getPhoneCode" type="primary" size="small" style="width: 100px;height: 40px;"  >发送验证码</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeValidPhone">取 消</el-button>
        <el-button type="primary" @click="submitPhoneValid">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="邮箱验证" :visible.sync="validEmailDialog" width="30%" :wrapper-closable="false" :before-close="closeValidEmail">
      <el-form :model="validEmailForm">
        <el-form-item label="邮箱" label-width="100px">
          <el-input v-model="validEmailForm.email" auhonetocomplete="off" disabled></el-input>
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="验证码" label-width="100px" style="flex:1;">
            <el-input v-model="validEmailForm.code" autocomplete="off" style="width:300px"></el-input>
          </el-form-item>
          <el-button @click="getEmailCode" type="primary" size="small" style="width: 100px;height: 40px;"  >发送验证码</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeValidEmail">取 消</el-button>
        <el-button type="primary" @click="submitEmailValid">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改头像" :visible.sync="editAvatar" width="20%" :wrapper-closable="false" :before-close="closeAvatarDialog">
      <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadAvatar">
        <img v-if="newAvatarUrl" :src="newAvatarUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAvatarDialog">取 消</el-button>
        <el-button type="primary" @click="submitUpdateAvatar">确 定</el-button>
      </div>
    </el-dialog>

    <el-col :span="8">
      <el-card class="profile-card">
        <template #header> 个人信息 </template>
        <div class="avatar">
          <el-avatar shape="circle"
                     style="cursor: pointer"
                     :size="150"
                     :src="userAvatar"
                     @click.native="updateAvatar"></el-avatar>
        </div>

        <ul>
          <li>
            <i class="el-icon-user" style="margin-right: 10px;"></i> 用户名 <span>{{ $store.state.userName }}</span>
          </li>
          <li>
            <i class="el-icon-star-off" style="margin-right: 10px;"></i> 签名 <span>{{ userInfo.sign }}</span>
          </li>
          <li>
            <i class="el-icon-coin" style="margin-right: 10px;"></i> 用户角色 <span>{{ userInfo.roleName }}</span>
          </li>
          <li>
            <i class="el-icon-mobile-phone" style="margin-right: 10px;"></i> 手机号码 <span>{{ userInfo.phone }}</span>
          </li>
          <li>
            <i class="el-icon-message" style="margin-right: 10px;"></i> 用户邮箱 <span>{{ userInfo.email }}</span>
          </li>
          <li>
            <i class="el-icon-place" style="margin-right: 10px;"></i> 所属组织 <span>{{ userInfo.userName }}</span>
          </li>
          <li>
            <i class="el-icon-school" style="margin-right: 10px;"></i> 地址 <span>{{ userInfo.address }}</span>
          </li>
          <li>
            <i class="el-icon-alarm-clock" style="margin-right: 10px;"></i> 最近登录时间 <span>{{ userInfo.lastLoginTime }}</span>
          </li>
          <li>
            <i class="el-icon-timer" style="margin-right: 10px;"></i> 创建日期 <span>{{ userInfo.createTime }}</span>
          </li>
        </ul>
      </el-card>
    </el-col>
    <el-col :span="16">
      <el-card>
        <template #header> 基本信息 </template>
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本资料" name="info">
            <el-form :model="userInfo" status-icon label-width="100px" class="demo-ruleForm">
              <el-form-item label="用户名" prop="userName" >
                <el-input v-model="userInfo.userName" show-word-limit maxlength="10" clearable></el-input>
              </el-form-item>
              <el-form-item label="签名" prop="sign" >
                <el-input v-model="userInfo.sign" show-word-limit maxlength="20" clearable></el-input>
              </el-form-item>
              <div style="display: flex">
                <el-form-item label="邮箱" prop="email" style="flex:1;">
                  <el-input v-model="currentEmail" show-word-limit maxlength="50" clearable style="width: 800px;"></el-input>
                </el-form-item>
                <el-button  type="primary" @click="handleValidEmail" size="mini" style="width: 100px;height: 40px;">邮箱验证</el-button>
              </div>

              <div style="display: flex">
                <el-form-item label="手机号码" prop="phone" style="flex:1;">
                  <el-input v-model="currentPhone" show-word-limit maxlength="11" clearable style="width: 800px;"></el-input>
                </el-form-item>
                <el-button  type="primary" @click="handleValidPhone" size="mini" style="width: 100px;height: 40px;">手机号码验证</el-button>
              </div>

              <el-form-item label="地址" prop="address">
                <el-input type="textarea" v-model="userInfo.address" show-word-limit maxlength="100" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitUserBaseInfo" :loading="saveLoading">保存</el-button>
                <el-button type="info" @click="refresh" >刷新</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="password">
            <el-form :model="editPwd" status-icon label-width="100px" class="demo-ruleForm">
              <el-form-item label="旧密码" prop="oldPwd" >
                <el-input type="password" v-model="editPwd.oldPwd"  clearable></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPwd" >
                <el-input type="password" v-model="editPwd.newPwd"  clearable></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmNewPwd" >
                <el-input type="password" v-model="editPwd.confirmNewPwd" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="editUserPwd" :loading="editPwdLoading">保存</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="第三方登录" name="third" lazy>

          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
import { getLoginUserId } from "@/utils/userToken";
import { getUserInfo,
  phoneCode,
  validPhone,
  editUserBaseInfo,
  sendEmail,
  validEmail,
  updateUserPwd,
  updateUserAvatar } from "@/api/user";
import { VALID_PHONE_CODE_TYPE } from "@/utils/constants";
import { uploadFile } from "@/api/file";
import { USER_AVATAR } from "@/utils/fileType";

export default {
  data() {
    return {
      userInfo: {},
      activeName: "info",
      validPhoneForm: {
        phone: "",
        code: ""
      },
      currentPhone: "",
      currentEmail: "",
      validEmailForm: {
        email: "",
        code: ""
      },
      validPhoneDialog: false,
      validEmailDialog: false,
      validEmail: "",
      canPhoneSave: true,
      canEmailSave: true,
      saveLoading: false,
      editPwdLoading: false,
      editPwd: {
        userId: "",
        oldPwd: "",
        newPwd: "",
        confirmNewPwd: ""
      },
      editAvatar: false,
      newAvatarUrl: '',
      userAvatar: this.$store.state.userAvatar
    }
  },

  created() {
    this.fetchUserInfo();
    console.log('123=', this.$store.state.userAvatar)
  },

  watch: {
    currentPhone(newVal, oldVal) {
      if (newVal && oldVal && newVal !== oldVal) {
        this.currentPhone = newVal;
        this.canPhoneSave = false;
      }
    },

    currentEmail(newVal, oldVal) {
      console.log(newVal, oldVal)
      if (newVal && oldVal && newVal !== oldVal) {
        this.currentEmail = newVal;
        this.canEmailSave = false;
      }
    }
  },

  methods: {
    // 获取手机号码验证码
    getPhoneCode() {
      phoneCode(this.validPhoneForm.phone, VALID_PHONE_CODE_TYPE).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '验证码发送成功,请于一分钟内完成验证',
            type: 'success',
            duration: 3000
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 打开修改头像的弹框
    updateAvatar() {
      this.editAvatar = true;
    },

    // 提交修改头像
    submitUpdateAvatar() {
      updateUserAvatar(this.newAvatarUrl).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '头像修改成功',
            type: 'success',
            duration: 1500
          });
          this.$store.commit('updateUserAvatar', this.newAvatarUrl);
          this.userAvatar = this.newAvatarUrl;
          this.closeAvatarDialog();
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    uploadAvatar(file) {
      const data = new FormData();
      data.append('file', file.file);
      data.append('type', USER_AVATAR);
      uploadFile(data).then(response => {
        // 将之前的图片删除
        if(response.code === 200) {
          this.newAvatarUrl = response.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: response.message,
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    // 获取用户信息
    fetchUserInfo() {
      getUserInfo(getLoginUserId()).then(res => {
        if (res.code === 200) {
          this.userInfo = res.data;
          this.currentPhone = res.data.phone;
          this.currentEmail = res.data.email;
          this.editPwd.userId = res.data.userId;
        }
      })
    },

    // 编辑用户基本信息
    submitUserBaseInfo() {

      if (!this.canPhoneSave && this.currentPhone !== this.userInfo.phone) {
        this.$notify.error({
          title: '错误',
          message: '该手机号码未验证',
          duration: 1500
        });
        return;
      }

      if (!this.canEmailSave && this.currentEmail !== this.userInfo.email) {
        this.$notify.error({
          title: '错误',
          message: '该邮箱未验证',
          duration: 1500
        });
        return;
      }

      if (!this.userInfo.userName) {
        this.$notify.error({
          title: '错误',
          message: '用户名不能为空',
          duration: 1500
        });
        return;
      }
      this.saveLoading = true;

      this.userInfo.phone = this.currentPhone;
      this.userInfo.email = this.currentEmail;
      editUserBaseInfo(this.userInfo).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 1500
          });
          this.$store.commit('updateUserName', this.userInfo.userName);
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
        this.saveLoading = false;
        this.fetchUserInfo();
      })
    },

    submitPhoneValid() {
      if (!this.validPhoneForm.code) {
        this.$notify.error({
          title: '错误',
          message: '请输入验证码',
          duration: 1500
        });
        return;
      }

      validPhone(this.validPhoneForm).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '手机号码认证成功',
            type: 'success',
            duration: 1500
          });
          this.canPhoneSave = true;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
        this.closeValidPhone();
      })
    },

    // 验证手机号码
    handleValidPhone() {
      this.validPhoneDialog = true;
      this.validPhoneForm.phone = this.currentPhone;
    },

    // 打开验证邮箱的弹框
    handleValidEmail() {
      this.validEmailDialog = true;
      this.validEmailForm.email = this.currentEmail;
    },

    // 获取邮箱验证码
    getEmailCode() {
      sendEmail(this.validEmailForm.email).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '验证码发送成功,请于一分钟内完成验证',
            type: 'success',
            duration: 3000
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })

    },

    // 关闭验证手机号码的弹框
    closeValidPhone() {
      this.validPhoneDialog = false;
      this.validPhoneForm.phone = '';
      this.validPhoneForm.code = '';
    },

    // 关闭验证邮箱的弹框
    closeValidEmail() {
      this.validEmailDialog = false;
      this.validEmailForm.email = '';
      this.validEmailForm.code = '';
    },

    // 关闭修改头像的弹框
    closeAvatarDialog() {
      this.newAvatarUrl = '';
      this.editAvatar = false;
    },

    refresh() {
      this.fetchUserInfo();
    },

    submitEmailValid() {
      if (!this.validEmailForm.code) {
        this.$notify.error({
          title: '错误',
          message: '请输入验证码',
          duration: 1500
        });
        return;
      }

      validEmail(this.validEmailForm).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '邮箱认证成功',
            type: 'success',
            duration: 1500
          });
          this.canEmailSave = true;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
        this.closeValidEmail();
      })
    },

    // 修改密码
    editUserPwd() {
      if (!this.editPwd.oldPwd) {
        this.$notify.error({
          title: '错误',
          message: '请输入旧密码',
          duration: 1500
        });
        return;
      }

      if (!this.editPwd.newPwd) {
        this.$notify.error({
          title: '错误',
          message: '请输入新密码',
          duration: 1500
        });
        return;
      }

      if (!this.editPwd.confirmNewPwd) {
        this.$notify.error({
          title: '错误',
          message: '请输入确认密码',
          duration: 1500
        });
        return;
      }

      if (this.editPwd.confirmNewPwd !== this.editPwd.newPwd) {
        this.$notify.error({
          title: '错误',
          message: '新密码与确认密码不一致',
          duration: 1500
        });
        return;
      }

      this.editPwdLoading = true;
      updateUserPwd(this.editPwd).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '密码修改成功',
            type: 'success',
            duration: 1500
          });
          this.editPwd = {}
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
        this.editPwdLoading = false;
      })
    },


  },

}
</script>


<style scoped lang="scss">
.profile-card {
  .avatar {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
  }
  .el-card__body .avatar {
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
  }
  .el-card__body .avatar .el-avatar  {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  ul {
    list-style: none;
    padding: 0;
    li {
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      &:last-child {
        border-bottom: none;
        padding-top: 12px;
      }
      span {
        float: right;
      }
    }
  }
}

</style>
